package org.urbansoft.iso;

/**
 * Implements the Padder interface for padding strings and byte arrays on the
 * left.
 * 
 * @author joconnor
 * @version $Revision: 2594 $ $Date: 2008-01-22 14:41:31 -0200 (Tue, 22 Jan
 *          2008) $
 */
public class LeftPadder implements Padder {
	/**
	 * A padder for padding zeros on the left. This is very common in numeric
	 * fields.
	 */
	public static final LeftPadder ZERO_PADDER = new LeftPadder('0');

	private char pad;

	/**
	 * Creates a Left Padder with a specific pad character.
	 * 
	 * @param pad
	 *            The padding character. For binary padders, the pad character
	 *            is truncated to lower order byte.
	 */
	public LeftPadder(char pad) {
		this.pad = pad;
	}

	/**
	 * @see org.jpos.iso.Padder#pad(java.lang.String, int, char)
	 */
	public String pad(String data, int maxLength) throws ISOException {
		StringBuffer padded = new StringBuffer(maxLength);
		int len = data.length();
		if (len > maxLength) {
			throw new ISOException("Data is too long. Max = " + maxLength);
		} else {
			for (int i = maxLength - len; i > 0; i--) {
				padded.append(pad);
			}
			padded.append(data);
		}
		return padded.toString();
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see org.jpos.iso.Padder#unpad(java.lang.String, char)
	 */
	public String unpad(String paddedData) {
		int i = 0;
		int len = paddedData.length();
		while (i < len) {
			if (paddedData.charAt(i) != pad) {
				return paddedData.substring(i);
			}
			i++;
		}
		return "";
	}
}